//
//  XXTimer.m
//  XiuXiuTuanGou
//
//  Created by 张敬 on 2019/5/15.
//  Copyright © 2019年 XiuXiuTuanGou. All rights reserved.
//

#import "TJTimer.h"

@implementation TJTimer
{
    dispatch_source_t _timer;
}


- (instancetype)init{
    
    self = [super init];
    if (self) {
        _time = 60;
    }
    return self;
}


//60秒倒计时
-(void)startTimer
{
    __block NSInteger timeout = _time; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    
    kWeakSelf(self)
    dispatch_source_set_event_handler(_timer, ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (timeout == 0) {
                
                if (weakself.endBlock) {
                    weakself.endBlock();
                }
                
                timeout = _time;
                dispatch_cancel(_timer);
                
            } else {
               
                if (weakself.doingBlock) {
                    weakself.doingBlock(timeout);
                }

              timeout--;
            }
        });
        
    });
    dispatch_resume(_timer);
}

- (void)cancelTimer{
    if (!_timer) {
        dispatch_cancel(_timer);
        _timer = nil;
    }
}

@end
